//
//  HBAppConfig.m
//  HeartBeat
//
//  Created by karong on 2023/8/23.
//

#import "HBAppConfig.h"

@implementation HBAppConfig
static HBAppConfig *instanceAppConfig = nil;
+ (NSArray *)mj_ignoredPropertyNames {
    return @[@"aes_key", @"aes_iv"];
}

+ (instancetype)defaultSession {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instanceAppConfig = [[self alloc] init];
    });
    return instanceAppConfig;
}

- (instancetype)init {
    if([appUserDefaults objectForKey:@"HBAppConfig"]) {
        self = [[HBAppConfig alloc] mj_setKeyValues:[appUserDefaults objectForKey:@"HBAppConfig"]];
    }
    else {
        self = [super init];
        self.languageType = 2;
        self.isAutoPay = YES;
        self.startConfig = [HBStartConfig new];
    }
    self.startConfig.click_to_skip_login = 1;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(save) name:UIApplicationWillTerminateNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(save) name:UIApplicationDidEnterBackgroundNotification object:nil];
    return self;
}

- (void)save {
    @try {
        [appUserDefaults setObject:instanceAppConfig.mj_keyValues forKey:@"HBAppConfig"];
    } @catch (NSException *exception) {
        [appUserDefaults removeObjectForKey:@"HBAppConfig"];
    } @finally {
        [appUserDefaults synchronize];
    }
}

- (NSString *)aes_key {
    if (!_aes_key) {
        NSString * host = API_HEARTBEAT_HOST;
        NSString * md5 = [host.lowercaseString md5String];
        _aes_key = [md5 substringWithRange:NSMakeRange(8, 16)];
    }
    return _aes_key;
}

- (NSString *)aes_iv {
    if (!_aes_iv) {
        unsigned long len;
        len = [self.aes_key length];
        unichar a[len];
        for(int i = 0; i < len; i++) {
            unichar c = [self.aes_key characterAtIndex:len-i-1];
            a[i] = c;
        }
        _aes_iv = [NSString stringWithCharacters:a length:len];
    }
    return _aes_iv;
}
@end

@implementation HBStartConfig

@end
